﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace FileLog
{
    public static class AsyncLockProvider<T> where T : notnull
    {
        static readonly ConcurrentDictionary<T, SemaphoreSlim> _lockDictionary =
            new ConcurrentDictionary<T, SemaphoreSlim>();
        public static async Task AsyncLock(T idToLock)
        {
            await _lockDictionary.GetOrAdd(idToLock, new SemaphoreSlim(1, 1)).WaitAsync();
        }

        public static void Release(T idToLock)
        {
            if (_lockDictionary.TryGetValue(idToLock, out var value))
            {
                value.Release();
            }
        }

        public static void RemovecLock(T idToLock)
        {
            if (_lockDictionary.Remove(idToLock, out var value))
            {
                using (value) { value.Release(); }
            }
        }
    }
}
